package com.example.goods.controller;

import com.example.goods.bean.Cart;
import com.example.goods.bean.User;
import com.example.goods.common.Const;
import com.example.goods.common.ResultResponse;
import com.example.goods.service.CartService;
import com.example.goods.vo.CartVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
import java.util.Optional;

/**
 * Created by IntelliJ IDEA.
 *
 * @author ouyangzhixiang
 * @date 2018/7/6
 */
@RestController
@RequestMapping("/cart/")
public class CartContorller {
    @Autowired
    private CartService cartService;

    /**
     * 添加商品到购物
     * @param session
     * @param count
     * @param productId
     * @return
     */
    @GetMapping(value = "add")
    public ResultResponse<Cart> add(HttpSession session, Integer count, String productId) {
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ResultResponse.createByErrorMessage("用户未登录");
        }
        return cartService.addCart(user.getId(), productId, count);
    }

    /**
     * 查询购物车中商品
     * @param id
     * @return
     */
    @GetMapping("select/{id}")
    public ResultResponse<Optional<Cart>> select(@PathVariable("id") Integer id){
        return cartService.select(id);
    }

    /**
     *删除购物车
     * @param id
     */
    @GetMapping("delete/{id}")
    public void delete(@PathVariable("id") Integer id){
        cartService.deleteCart(id);
    }

    /**
     * 更新购物
     * @param session
     * @param productId
     * @param quantity
     * @return
     */
    @GetMapping("update")
    public ResultResponse<Cart> update(HttpSession session,String productId,Integer quantity){
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ResultResponse.createByErrorMessage("用户未登录");
        }
        return cartService.update(user.getId(),productId,quantity);
    }

    @GetMapping("checked")
    public ResultResponse<Cart> checked(HttpSession session,String productId,Integer checked){
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ResultResponse.createByErrorMessage("用户未登录");
        }
        return cartService.checked(user.getId(),productId,checked);
    }


    @GetMapping("lists")
    public ResultResponse<CartVO>findList(){
        return cartService.findList();
    }
}
